//
//  ClubMineViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import UIKit
import swiftScan

class ClubMineViewController: ClubBaseViewController {
    
    private var navView = MineNavView()
    private var topView = MineTopView()
    private var gongNengView = MineGongNengView()
    private var gameView = MineGameView()
    private var scanVC = ClubScanViewController()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.subviews{
            navView
            topView
            gongNengView
            gameView
        }
        
        navView.leading(0).trailing(0).top(0).height(170.0.Scale)
        topView.leading(0).trailing(0).top(170.0.Scale).height(140.0.Scale)
        gongNengView.leading(0).trailing(0).height(120.0.Scale)
        gongNengView.Top == topView.Bottom
        gameView.leading(0).trailing(0).height(208.0.Scale)
        gameView.Top == gongNengView.Bottom
        
        navView.settingBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0{
                let settingVC = ClubSettingViewController()
                settingVC.fromMineVC = true
                self.navigationController?.pushViewController(settingVC, animated: true)
            } else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        navView.scanBlock = {
            self.scanButtonClick()
        }
        navView.msgBlock = {
            self.clickMessageButton()
        }
        navView.userInfoBlock = {
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            self.navigationController?.pushViewController(ClubMineInfoViewController(), animated: true)
        }
        topView.signinBlock = {
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            let signinVC = ClubSigninViewController()
            signinVC.updateBlock = {
                self.loadData()
            }
            self.navigationController?.pushViewController(signinVC, animated: true)
        }
        topView.integralBlock = {
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            self.navigationController?.pushViewController(ClubIntegralStoreViewController(), animated: true)
        }
        gongNengView.pushBlock = { md in
            let type = md.type
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            if type == "304" {
                //我的收藏
                self.navigationController?.pushViewController(ClubMyCollectViewController(), animated: true)
            }else if type == "317" {
                //我的评论
                self.navigationController?.pushViewController(ClubMyCommitViewController(), animated: true)
            }else if type == "335" {
                //我的关注
                self.navigationController?.pushViewController(ClubMyCollectViewController(), animated: true)
            }else if type == "315" {
                //我的资产
                self.navigationController?.pushViewController(ClubPropertyViewController(), animated: true)
            }else if type == "307" {
                //客服中心
                let webView = ClubWebViewController()
                webView.urlString = md.url
                webView.titleName = "客服中心"
                self.navigationController?.pushViewController(webView, animated: true)
            }else if type == "308" {
                //安全中心
                self.navigationController?.pushViewController(ClubSafeViewController(), animated: true)
            }else if type == "318" {
                //关于我们
                let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
                let bundleVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
                let url = RaeRequestParameterConfig.shared.baseUrlStr + "ct=app&ac=contact&ios=1&h5=1&version=\(version)(\(bundleVersion))"
                let webView = ClubWebViewController()
                webView.urlString = url
                webView.titleName = "个人中心"
                self.navigationController?.pushViewController(webView, animated: true)
            }else if type == "306" {
                //系统设置
                self.navigationController?.pushViewController(ClubSettingViewController(), animated: true)
            }
        }

        NotificationCenter.default.addObserver(self, selector: #selector(pushToGameDetailVC), name: .mineToGameDetailVC, object: nil)
    }
    
    
    private func loadData(){
        
        var user_id = ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            user_id = uid
        }
        Task {
            let res = await network.request(.mineInfo(uid: user_id),type: ClubMineModel.self)
            if res.isSuccess, let model = res.model {
                
                self.navView.model = model.user
                self.topView.model = model.user
                ClubUser = model.user
                var gongNengModels = [ClubMineNavDataModel]()
                var gameModels = [ClubMineNavDataModel]()
                for md in model.nav {
                    if md.title == "常用功能" {
                        gongNengModels.append(contentsOf: md.data)
                    }else if md.title == "服务" {
                        gongNengModels.append(contentsOf: md.data)
                    }else if md.title == "热门游戏" {
                        gameModels.append(contentsOf: md.data)
                    }
                }
                self.gongNengView.sourceData = gongNengModels
                self.gameView.sourceData = gameModels
            }
        }
    }
}


//MARK: action
extension ClubMineViewController {
    
    @objc private func pushToGameDetailVC(_ noti: Notification){
        
        guard let gameID = noti.userInfo?["gameId"] as? String else { return }
        let gameVC = ClubGameDetailViewController()
        gameVC.gameId = gameID
        self.navigationController?.pushViewController(gameVC, animated: true)
    }
    
    @objc private func clickMessageButton(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            self.navigationController?.pushViewController(ClubMessageViewController(), animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}

//MARK: scan
extension ClubMineViewController: LBXScanViewControllerDelegate {
    
    private func scanButtonClick(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            //设置扫码区域参数
            var style = LBXScanViewStyle()
            style.centerUpOffset = 44
            style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner
            style.photoframeLineW = 2
            style.photoframeAngleW = 18
            style.photoframeAngleH = 18
            style.isNeedShowRetangle = false

            style.anmiationStyle = LBXScanViewAnimationStyle.LineMove

            style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)

            style.animationImage = UIImage(named: "qrcode_Scan_weixin_Line")

//            let vc = ClubScanViewController()
            scanVC.scanStyle = style
            scanVC.readyString = "加载中"
            scanVC.scanResultDelegate = self
            let v = UIView()
            v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
            v.backgroundColor = .clear
            self.present(scanVC, animated: true)
            scanVC.qRScanView?.addSubview(v)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400)) {
            if scanResult.strScanned?.hasPrefix("LoginToken") == true {
                self.scanVC.dismiss(animated: true) {
                    let vc = ClubScanLoginViewController()
                    vc.strScanned = scanResult.strScanned ?? ""
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            } else if scanResult.strScanned?.hasPrefix("http") == true{
                let url = URL(string: scanResult.strScanned ?? "")
                if url != nil {
                    UIApplication.shared.open(url!)
                } else {
                    "二维码无效".toast_error
                }
            } else {
                "二维码无效".toast_error
            }
        }
    }
}
